package com.dlc.apk.utils;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.dlc.apk.R;
import com.dlc.apk.base.BaseApp;

import java.lang.ref.WeakReference;

public class ToastUtil {
    private static WeakReference<Toast> mToastRef = null;

    public ToastUtil() {
    }

    /**
     * 默认系统原生toast
     *
     * @param text
     */
    public static void show(String text) {
        Toast toast;
        if (mToastRef != null && (toast = (Toast) mToastRef.get()) != null) {
            toast.cancel();
        }

        toast = Toast.makeText(BaseApp.Companion.getInstance(), text, Toast.LENGTH_SHORT);
        mToastRef = new WeakReference(toast);
        toast.show();
    }

    /**
     * 自定义布局 toast
     *
     * @param context
     * @param text
     */
    public static void showOne(Context context, String text, int icon) {
        /*Toast toast;
        if (mToastRef != null && (toast = (Toast) mToastRef.get()) != null) {
            toast.cancel();
        }

        toast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);
        mToastRef = new WeakReference(toast);
        toast.show();*/

        Toast toast;
        if (mToastRef != null && (toast = (Toast) mToastRef.get()) != null) {
            toast.cancel();
        }
        toast = new Toast(context);
        mToastRef = new WeakReference(toast);
        // 获取LayoutInflater对象
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // 由layout文件创建一个View对象
        View layout = inflater.inflate(R.layout.layout_common_dialog, null);

        TextView tvMessage = layout.findViewById(R.id.tv_message);
        ImageView ivIcon = layout.findViewById(R.id.iv_icon);
        ivIcon.setImageResource(icon);

        tvMessage.setText(text);
        toast.setView(layout);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 自定义布局 toast
     *
     * @param context
     * @param resId
     */
    public static void showOne(Context context, int resId) {
        showOne(context, context.getResources().getString(resId), R.mipmap.ic_cg);
    }

    /**
     * 自定义布局 toast
     *
     * @param context
     * @param text
     */
    public static void show(Context context, String text) {
        showOne(context, text, R.mipmap.ic_info);
    }


    /**
     * 自定义布局toast
     *
     * @param context
     * @param resId
     */
    public static void show(Context context, int resId) {
        //Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
        showOne(context, resId);
    }
}